using Microsoft.AspNetCore.Mvc;
using 后端服务.Models;
using 后端服务.Services;

namespace 后端服务.Controllers
{
    /// <summary>
    /// 认证控制器，处理用户注册和登录请求
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly AuthService _authService;
    
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="authService">认证服务</param>
        public AuthController(AuthService authService)
        {
            _authService = authService;
        }

        /// <summary>
        /// 用户注册接口
        /// </summary>
        /// <param name="model">注册模型，包含用户名和密码</param>
        /// <returns>注册成功返回用户信息和令牌，失败返回错误信息</returns>
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterModel model)
        {
            // 验证模型状态
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            try
            {
                // 获取设备信息
                string deviceInfo = GetDeviceInfo();
                
                // 调用注册服务
                var (user, token, refreshToken) = await _authService.Register(model.Username, model.Password, deviceInfo);
            
                // 返回用户信息和令牌
                return Ok(new
                {
                    username = user.Username,
                    isAdmin = user.IsAdmin,
                    token,            // JWT访问令牌
                    refreshToken      // 用于刷新访问令牌的刷新令牌
                });
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 用户登录接口
        /// </summary>
        /// <param name="model">登录模型，包含用户名和密码</param>
        /// <returns>登录成功返回用户信息和令牌，失败返回未授权状态</returns>
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginModel model)
        {
            // 验证模型状态
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            // 获取设备信息
            string deviceInfo = GetDeviceInfo();

            // 验证用户身份
            var result = await _authService.Authenticate(model.Username, model.Password, deviceInfo);
            if (result == null)
                return Unauthorized(); // 验证失败返回401状态码

            var (user, token, refreshToken) = result.Value;
            
            // 返回用户信息和令牌
            return Ok(new
            {
                username = user.Username,
                isAdmin = user.IsAdmin,
                token,            // JWT访问令牌
                refreshToken      // 刷新令牌
            });
        }

        /// <summary>
        /// 刷新访问令牌接口
        /// </summary>
        /// <param name="model">刷新令牌模型</param>
        /// <returns>成功返回新的访问令牌和刷新令牌，失败返回未授权状态</returns>
        [HttpPost("refresh")]
        public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenModel model)
        {
            if (string.IsNullOrEmpty(model.RefreshToken))
                return BadRequest("刷新令牌不能为空");

            // 获取设备信息
            string deviceInfo = GetDeviceInfo();

            // 尝试刷新令牌
            var result = await _authService.RefreshToken(model.RefreshToken, deviceInfo);
            if (result == null)
                return Unauthorized(); // 刷新失败返回401状态码

            var (user, token, newRefreshToken) = result.Value;

            // 返回新的令牌
            return Ok(new
            {
                username = user.Username,
                isAdmin = user.IsAdmin,
                token,            // 新的JWT访问令牌
                refreshToken = newRefreshToken  // 新的刷新令牌
            });
        }

        /// <summary>
        /// 获取客户端设备信息
        /// </summary>
        /// <returns>设备信息字符串</returns>
        private string GetDeviceInfo()
        {
            // 获取用户代理
            string userAgent = Request.Headers.UserAgent.ToString();
            
            // 获取客户端IP地址
            string ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
            
            return $"{userAgent}|{ipAddress}";
        }
    }

    /// <summary>
    /// 用户注册请求模型
    /// </summary>
    public class RegisterModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
    }

    /// <summary>
    /// 用户登录请求模型
    /// </summary>
    public class LoginModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
    }

    /// <summary>
    /// 刷新令牌请求模型
    /// </summary>
    public class RefreshTokenModel
    {
        /// <summary>
        /// 刷新令牌
        /// </summary>
        public string RefreshToken { get; set; }
    }
}